<template>
  <div class="water-mark" ref="root">
    <canvas ref="single" class="single" />
    <canvas ref="repeat" />
  </div>
</template>
<script>
export default {
  name: 'WaterMark',
  props: {
    config: {
      type: Object
    }
  },
  data () {
    const { text, width, height, color, font, rotate } = this.config || {}
    return {
      single: null,
      repeat: null,
      root: null,
      set: {
        text: text || 'admin',
        width: width || 150,
        height: height || 60,
        color: color || 'rgba(102, 108, 222, 0.2)',
        font: font || '14px serif',
        rotate: rotate || 10
      }
    }
  },
  mounted () {
    this.init()
    window.onresize = () => {
      this.init()
    }
  },
  methods: {
    init () {
      this.single = this.$refs.single
      this.repeat = this.$refs.repeat
      this.root = this.$refs.root
      this.updateCanvas()
    },
    generateSingle () {
      const { width, height, font, color, rotate, text } = this.set
      this.single.width = width
      this.single.height = height
      this.single.style.width = width + 'px'
      this.single.style.height = height + 'px'
      const singleCtx = this.single.getContext('2d')
      singleCtx.clearRect(0, 0, width, height)
      singleCtx.font = font
      singleCtx.rotate((-rotate * Math.PI) / 180)
      singleCtx.fillStyle = color
      singleCtx.fillText(text, 0, height)
    },
    generateRepeat () {
      const { clientWidth, clientHeight } = this.root
      this.repeat.width = clientWidth
      this.repeat.height = clientHeight
      const repeatCtx = this.repeat.getContext('2d')
      repeatCtx.clearRect(0, 0, clientWidth, clientHeight)
      repeatCtx.fillStyle = repeatCtx.createPattern(this.single, 'repeat')
      repeatCtx.fillRect(0, 0, clientWidth, clientHeight)
    },
    updateCanvas () {
      this.generateSingle()
      this.generateRepeat()
    }
  }
}
</script>
<style lang="less">
  .water-mark {
    top: 0;
    left: 0;
    position: fixed;
    pointer-events: none;
    width: 100%;
    height: 100%;
    z-index: 99999;
    .single {
      display: none;
    }
  }
</style>
